package org.jeecg.modules.compilation.util;

import cn.hutool.core.io.file.FileReader;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.compilation.entity.CiDoc;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Slf4j
public class HtmlToString {

    public static void handleToHtml(CiDoc ciDoc , MultipartFile file) throws Exception {
        //创建文件夹
        String outPutPath = FolderUtil.setAbsolutePath(Constants.HOME_FOLDER_NAME + "handleHtml" + Constants.CURRENT_SEPARATOR);
        FolderUtil.createFolder(outPutPath);
        String pos = null;
        log.info("文件名称：{}",file.getOriginalFilename());
        //word文件转html
        if (file.getOriginalFilename().contains(".docx") || file.getOriginalFilename().contains(".DOCX")) {
           String path = AsposeUtil.ToDoc(ciDoc.getRealRoute());
            log.info("docx转doc换文件路径：{}",path);
           if ( path == null ){
               log.info("Aspose-word转换失败！！");
               pos = WordToHtml.docx(path, outPutPath, ciDoc.getDocumentIdentifier() + ".htm");
               HtmlToString.htmlToString( pos , ciDoc , 0);
           }else {
               log.info("docx转doc处理路径：{}", path);
               pos = WordToHtml.dox(path, outPutPath, ciDoc.getDocumentIdentifier() + ".htm");
               //读取html文件内容
               HtmlToString.htmlToString(pos, ciDoc, 1);
           }
        } else {
            pos =  WordToHtml.dox( ciDoc.getRealRoute(), outPutPath , ciDoc.getDocumentIdentifier() + ".htm");
            //读取html文件内容
            HtmlToString.htmlToString( pos , ciDoc , 1);
        }
    }

    /**
     * 1 代表doc 2 代表docx
     * */
    public static void htmlToString(String filePath, CiDoc ciDoc, Integer num) {

        String str = FileReader.create(new File(filePath)).readString();
        str = str.replace("Evaluation Only. Created with Aspose.Words. Copyright 2003-2015 Aspose Pty Ltd.","");
        //将数字装换为中文
        str = CommonUtil.convertToChineseNumber(str);
        //正则表达式 指定添加空格
        str = CommonUtil.addition(str);
        if ( num == 1) {
            String tempStyle = str.substring(str.indexOf("<style"));
            ciDoc.setHtmlStyle(tempStyle.substring(str.substring(str.indexOf("<style")).indexOf(">") + 1, tempStyle.indexOf("</style>")));
            String tempHtml = str.substring(str.indexOf("<body"));
            ciDoc.setHtmlText(tempHtml.substring(str.substring(str.indexOf("<body")).indexOf(">") + 1, tempHtml.indexOf("</body>")));
        } else {
            ciDoc.setHtmlText( str );
        }
    }

//    public static void main(String[] args) {
//        CiDoc ciDoc = new CiDoc();
//
//        String str = FileReader.create(new File("C:\\Users\\Lenovo\\Desktop\\烟草局制度汇编环境部署\\123.htm")).readString();
//        System.out.println(str);
//
//
//
//    }
}









//package org.jeecg.modules.ci.util;
//
//import cn.hutool.core.io.file.FileReader;
//import lombok.extern.slf4j.Slf4j;
//import org.jeecg.modules.ci.infrastructure.persistence.entity.CiDoc;
//import org.springframework.web.multipart.MultipartFile;
//import org.w3c.dom.Document;
//import org.w3c.dom.Element;
//import org.w3c.dom.NodeList;
//import org.xml.sax.SAXException;
//import org.xml.sax.SAXParseException;
//
//import javax.xml.parsers.DocumentBuilder;
//import javax.xml.parsers.DocumentBuilderFactory;
//import javax.xml.parsers.ParserConfigurationException;
//import javax.xml.transform.Transformer;
//import javax.xml.transform.TransformerConfigurationException;
//import javax.xml.transform.TransformerException;
//import javax.xml.transform.TransformerFactory;
//import javax.xml.transform.dom.DOMSource;
//import javax.xml.transform.stream.StreamResult;
//import java.io.ByteArrayInputStream;
//import java.io.File;
//import java.io.FileWriter;
//import java.io.IOException;
//import java.util.HashSet;
//import java.util.Set;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
//
//@Slf4j
//public class HtmlToString {
//
//    public static void handleToHtml(CiDoc ciDoc , MultipartFile file) throws Exception {
//        //创建文件夹
//        String outPutPath = FolderUtil.setAbsolutePath(Constants.HOME_FOLDER_NAME + "handleHtml" + Constants.CURRENT_SEPARATOR);
//        FolderUtil.createFolder(outPutPath);
//        String pos = null;
//        //word文件转html
//        if (file.getName().endsWith(".docx") || file.getName().endsWith(".DOCX")) {
//            pos =  WordToHtml.docx( ciDoc.getRealRoute(), outPutPath, ciDoc.getDocumentIdentifier() + ".htm");
//            //读取html文件内容
//            HtmlToString.htmlToString( pos , ciDoc , 0);
//        } else {
//            pos =  WordToHtml.dox( ciDoc.getRealRoute(), outPutPath , ciDoc.getDocumentIdentifier() + ".htm");
//            //读取html文件内容
//            HtmlToString.htmlToString( pos , ciDoc , 1);
//        }
//    }
//
//    /**
//     * 1 代表doc 2 代表docx
//     * */
//    public static void htmlToString(String filePath, CiDoc ciDoc, Integer num) {
//
//        String str = FileReader.create(new File(filePath)).readString();
//        if ( num == 1) {
//            String tempStyle = str.substring(str.indexOf("<style"));
//            ciDoc.setHtmlStyle(tempStyle.substring(str.substring(str.indexOf("<style")).indexOf(">") + 1, tempStyle.indexOf("</style>")));
//            String tempHtml = str.substring(str.indexOf("<body"));
//            ciDoc.setHtmlText(tempHtml.substring(str.substring(str.indexOf("<body")).indexOf(">") + 1, tempHtml.indexOf("</body>")));
//        } else {
//            ciDoc.setHtmlText( str );
//        }
//    }
//
////    public static void main(String[] args) {
//////        CiDoc ciDoc = new CiDoc();
//////
//////        String str = FileReader.create(new File("C:\\Users\\Lenovo\\Desktop\\新建文件夹\\123.htm")).readString();
//////        System.out.println(str);
////
////
////        WordToHtml.docx( "C:\\Users\\Lenovo\\Desktop\\烟草局制度汇编环境部署\\document\\164.中烟专〔2022〕11号（广东省中山市烟草专卖局关于印发 《中山市烟草专卖零售许可证办理轮候制度》的通知）.docx", "C:\\Users\\Lenovo\\Desktop\\烟草局制度汇编环境部署\\",  "123"+ ".htm");
////    }
//
//
//    public static void main(String[] args) throws ParserConfigurationException {
//        String docxlFile = "C:\\Users\\Lenovo\\Desktop\\烟草局制度汇编环境部署\\document\\111.中烟销〔2021〕9号（广东烟草中山市有限责任公司关于印发《广东烟草中山市有限责任公司20支全零售连锁网络建设实施意见（修订）》及相关配套文件的通知）.docx";
//        String pathHtml = "C:\\Users\\Lenovo\\Desktop\\烟草局制度汇编环境部署\\";
//        String nameHtml = "123456.htm";
//        try {
//            // 创建 DocumentBuilder 对象
//            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//            DocumentBuilder builder = factory.newDocumentBuilder();
//
//            WordToHtml.docx(docxlFile,pathHtml,nameHtml);
//            String htmlString = FileReader.create(new File(pathHtml +nameHtml )).readString();
//            if ( !htmlString.contains("<html>")) {
//                log.info("html文件不规范，进行校正....");
//                String a = "<!DOCTYPE html><html>\n" +
//                        "<head></head>\n" +
//                        "<body>\n";
//                String b = "</body></html>";
//                htmlString = a + htmlString + b;
//            }
//
//            Set<String> strRemve = new HashSet<>();
//            Pattern pattern = Pattern.compile("&[a-zA-Z0-9]+;");
//            Matcher matcher = pattern.matcher(htmlString);
//            while (matcher.find()) {
//                strRemve.add(matcher.group());
//            }
//            log.info("检测到未声明实体有：{}，",strRemve.toString());
//            for(String s: strRemve){
//                htmlString =  htmlString.replace(s,"—");
//            }
//
//            ByteArrayInputStream is = new ByteArrayInputStream(htmlString.getBytes());
//            // 添加实体声明
//            Document document = builder.parse(is);
//
//            // 3. 获取文档中的所有元素
//            NodeList elements = document.getElementsByTagName("*");
//
//            // 4. 遍历元素列表，将内联样式转换为外部样式表
//            for (int i = 0; i < elements.getLength(); i++) {
//                Element element = (Element) elements.item(i);
//                String inlineStyle = element.getAttribute("style");
//
//                if (!inlineStyle.isEmpty()) {
//                    // 创建一个外部样式表文件
//                    File cssFile = new File(pathHtml + "styles.css");
//
//                    // 将内联样式写入样式表文件
//                    FileWriter writer = new FileWriter(cssFile, true);
//                    writer.write(element.getTagName() + " { " + inlineStyle + " }\n");
//                    writer.close();
//
//                    // 移除内联样式
//                    element.removeAttribute("style");
//                }
//            }
//
//            // 5. 将修改后的文档保存到新的文件中
//            File output = new File(pathHtml + "output.html");
//            TransformerFactory transformerFactory = TransformerFactory.newInstance();
//            Transformer transformer = transformerFactory.newTransformer();
//            DOMSource source = new DOMSource(document);
//            StreamResult result = new StreamResult(output);
//            transformer.transform(source, result);
//
//            System.out.println("转换完成！");
//
//            System.out.println("css样式："+FileReader.create(new File("C:\\Users\\Lenovo\\Desktop\\烟草局制度汇编环境部署\\styles.css")).readString());
//            System.out.println("清除样式后："+FileReader.create(new File("C:\\Users\\Lenovo\\Desktop\\烟草局制度汇编环境部署\\output.html")).readString());
//
//
//        }catch (SAXParseException e){
//            log.info("{}",e);
//        } catch (TransformerConfigurationException e) {
//            log.info("{}",e);
//        } catch (ParserConfigurationException e) {
//            log.info("{}",e);
//        } catch (IOException e) {
//            log.info("{}",e);
//        } catch (TransformerException e) {
//            log.info("{}",e);
//        } catch (SAXException e) {
//            log.info("{}",e);
//        }
//    }
//}
